package com.mano233.server.config.security;

import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * SpringSecurity配置类
 * @author mano233
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final JwtAuthTokenFilter jwtAuthTokenFilter;
    private final UserCustomDetailServiceImpl userCustomDetailService;

    public SecurityConfig(UserCustomDetailServiceImpl userCustomDetailService, JwtAuthTokenFilter jwtAuthTokenFilter) {
        this.userCustomDetailService = userCustomDetailService;
        this.jwtAuthTokenFilter = jwtAuthTokenFilter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 身份验证配置，用于注入自定义身份验证Bean和密码校验规则
        auth.userDetailsService(userCustomDetailService);
    }

    /**
     * 匹配规则
     *
     * @param http http
     * @throws Exception ex
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭 CSRF 防护
        http.csrf().disable().headers().frameOptions().disable().and()
                // 开启跨域
                .cors().and()
                // 使用jwt关闭session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 验证请求
        http.authorizeRequests().antMatchers(HttpMethod.POST, "/login").permitAll();
        http.authorizeRequests().antMatchers("/event/**").hasRole("ADMIN");
        http.authorizeRequests().antMatchers("/form/**").hasRole("ADMIN").antMatchers("/user/*").hasRole("ADMIN");
        // http.authorizeRequests()
        //         .anyRequest()
        //         // 动态 url 认证
        //         .access("@rbacauthorityservice.hasPermission(request,authentication)");

        // 在UsernamePasswordAuthenticationFilter前添加jwtAuthTokenFilter过滤器来处理token
        http.addFilterBefore(jwtAuthTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
